package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exeception.UserNameUniqueException;
import com.atguigu.gulimall.member.vo.MemberLoginVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;
import org.springframework.web.bind.annotation.RequestBody;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRespVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        //检验唯一性

        String userName = vo.getUsername();
        String phone = vo.getMobile();
        checkPhoneUnique(phone);
        checkUserNameUnique(userName);
        //获得默认等级
        MemberLevelEntity memberLevel = memberLevelDao.selectOne(new QueryWrapper<MemberLevelEntity>().eq("default_status", 1));
        Long levelId = memberLevel.getId();
        //加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(vo.getPassword());
        //设置
        memberEntity.setLevelId(levelId);
        memberEntity.setUsername(userName);
        memberEntity.setMobile(phone);
        memberEntity.setPassword(encode);
        memberEntity.setCreateTime(new Date());
        this.save(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws UserNameUniqueException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new UserNameUniqueException();
        }
    }

    @Override
    public void checkUserNameUnique(String userName) throws UserNameUniqueException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0) {
            throw new UserNameUniqueException();
        }
    }

    @Override
    public MemberEntity login(@RequestBody MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (entity != null) {
            //有用户
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(password, entity.getPassword());
            if (matches) {
                return entity;
            }
            return null;
        } else {
            return null;
        }

    }

    @Override
    public MemberEntity login(SocialUser user) throws Exception {
        //查询是否注册
        //具有登录和注册逻辑
        String uid = user.getUid();

        //1、判断当前社交用户是否已经登录过系统
        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (entity != null) {
            //登录
            //更新token
            MemberEntity updateEntity = new MemberEntity();
            updateEntity.setId(entity.getId());
            updateEntity.setAccessToken(user.getAccess_token());
            updateEntity.setExpiresIn(user.getExpires_in());
            this.baseMapper.selectById(updateEntity);
            //更新token
            entity.setAccessToken(user.getAccess_token());
            entity.setExpiresIn(user.getExpires_in());
            return entity;
        } else {
            //注册+登录

            //通过token和uid查询用户信息
            HashMap<String, String> map = new HashMap<>();
            map.put("access_token", user.getAccess_token());
            map.put("uid", user.getUid());

            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), map);

            //插入新用户
            MemberEntity register = new MemberEntity();
            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                String nickName = (String) jsonObject.get("name");
                String gender = (String) jsonObject.get("gender");
                register.setNickname(nickName);
                register.setGender("m".equals(gender) ? 1 : 0);
            }

            register.setAccessToken(user.getAccess_token());
            register.setExpiresIn(user.getExpires_in());
            register.setSocialUid(user.getUid());
            register.setCreateTime(new Date());
            this.baseMapper.insert(register);

            return register;

        }
    }


}